const mongoose = require('mongoose')
const db = "mongodb://localhost/mall-db"
const glob = require('glob')
const {resolve} = require('path')


exports.initSchema = () => {
    glob.sync(resolve(__dirname, './schema', '**/*.js')).forEach(require)
}

exports.connect = () => {

    let maxConnectTimes = 0

    mongoose.connect(db)

    return new Promise((resolve, reject) => {
        // 连接数据库
        mongoose.connect(db)

        // 连接失败
        mongoose.connection.on('disconnected', (err) => {
            console.log(`***********连接失败***********`)
            if(maxConnectTimes <= 3) {
                // 进行重连
                maxConnectTimes ++
                mongoose.connect(db)
            } else {
                reject(err)
                throw new Error('数据库出现问题，程序无法搞定，请人为修理......')
            }
 
        })

        mongoose.connection.on('error', (err) => {
            console.log(`***********连接失败***********`)
            if(maxConnectTimes <= 3) {
                // 进行重连
                maxConnectTimes ++
                mongoose.connect(db)
            } else {
                reject(err)
                throw new Error('数据库出现问题，程序无法搞定，请人为修理......')
            }
        })
        // 数据库连接成功
        mongoose.connection.on('open', () => {
            console.log('MongoDB connected successfully')
            resolve()
        })
    })

}
